package com.djk.daily.thread.threadobjectclasscommonmethods;

/**
 * @Description 证明wait只释放当前的那把锁
 * @Author dujunkai
 * @Date 2021/7/3 20:54
 **/
public class WaitNotifyReleaseOwnMonitor {
    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA){
                    System.out.println("线程" + Thread.currentThread().getName() + "获取到resourceA锁");
                    synchronized (resourceB){
                        System.out.println("线程" + Thread.currentThread().getName() + "获取到resourceB锁");
                        try {
                            System.out.println("线程" + Thread.currentThread().getName() + "释放resourceA锁");
                            resourceA.wait();
                            System.out.println("线程" + Thread.currentThread().getName() + "执行完毕");
//                            resourceA.notify();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        },"Thread1");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (resourceA){
                    System.out.println("线程" + Thread.currentThread().getName() + "获取到resourceA锁");
                    System.out.println("线程" + Thread.currentThread().getName() + "尝试获取B锁。。。");
//                    resourceA.notify();
//                    try {
//                        resourceA.wait();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    synchronized (resourceB){
                        System.out.println("线程" + Thread.currentThread().getName() + "获取到resourceB锁");
                    }

                }
            }
        },"Thread2");

        thread1.start();
        thread2.start();
    }
}
